package com.wx.core.process.message.event;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.github.pagehelper.PageHelper;
import com.wx.core.process.BaseProcess;
import com.wx.core.process.BaseResult;
import com.wx.core.process.ProcessResult;
import com.wx.core.vo.MsgRequest;
import com.wx.entity.WxFansUser;
import com.wx.entity.WxFansUserExample;
import com.wx.service.WxFansUserService;
import com.zyht.bank.entity.AxdCustInfo;
import com.zyht.bank.entity.AxdCustInfoExample;
import com.zyht.bank.service.AxdCustInfoService;
import com.zyht.common.bean.ThreadPoolWrapperBean;
import com.zyht.common.inf.Observable;
import com.zyht.common.inf.Observer;

/**
 * @desc 取消关注时的流程处理
 * @author gavin
 * @date 2014-12-9
 * @time 上午11:09:35
 * @version 1.0
 */
public class UnsubscribeEventProcess extends BaseProcess implements Observable {

	@Resource
	private WxFansUserService wxFansUserService;

	@Resource
	private AxdCustInfoService axdCustInfoService;

	// 观察者
	private List<Observer> observerList = new ArrayList<Observer>();

	/**
	 * 订阅 or 取消订阅的服务
	 */
	@Override
	public BaseResult process(HttpServletRequest req, HttpServletResponse res, MsgRequest msgReq) {
		return unSubscribeWenXin(msgReq);
	}

	/**
	 * @author: gavin @date: 2015年7月13日 @Title: subscribeWenXin @Description:
	 *          取消关注，删除粉丝信息 @param @param msgReq @param @return 设定文件 @return int
	 *          返回类型 @throws
	 */
	private ProcessResult unSubscribeWenXin(MsgRequest msgReq) {
		ProcessResult result = new ProcessResult();
		// 不删除 修改状态为未关注
		Runnable run = () -> {
			WxFansUserExample example = new WxFansUserExample();
			example.createCriteria().andOpenidEqualTo(msgReq.getFromUserName());
			WxFansUser record = new WxFansUser();
			record.setSubscribe(0);

			// 处理用户绑定状态
			wxFansUserService.updateByExampleSelective(record, example);
			PageHelper.startPage(1, 1);
			List<WxFansUser> list = wxFansUserService.selectByExample(example);
			if (list.size() > 0) {
				WxFansUser wxFansUser = list.get(0);
				AxdCustInfoExample custInfoExample = new AxdCustInfoExample();
				custInfoExample.createCriteria().andBandingStatusEqualTo("1").andFanUserIdEqualTo(wxFansUser.getId());
				PageHelper.startPage(1, 1);
				List<AxdCustInfo> list2 = axdCustInfoService.list(custInfoExample);
				list2.forEach(custInfo -> {
					custInfo.setOpenid("1");
					axdCustInfoService.updateById(custInfo);
				});
			}

		};
		ThreadPoolWrapperBean.getThreadPool().putThread(run);
		return result;
	}

	@Override
	public void notifyObservers(Object arg) {
		for (Observer o : observerList) {
			o.update(this, arg);
		}
	}

	public void setObservers(List<Observer> observers) {
		if (null != observers) {
			this.observerList.addAll(observers);
		}
	}
}